<template>
  <div class="enterprise-assistant">
    <!-- 上部分 - 企业经营分析工具 -->
    <div class="analysis-tools-section">
      <analysis-tools-bar @tool-selected="handleToolSelected" />
    </div>
    
    <!-- 下部分 - 三栏布局 -->
    <div class="main-content">
      <!-- 左侧 - 对话主题列表 -->
      <div class="left-panel">
        <chat-topic-list 
          :topics="chatTopics" 
          :active-topic-id="activeTopicId"
          @select-topic="handleSelectTopic"
          @create-topic="handleCreateTopic"
          @rename-topic="handleRenameTopic"
          @delete-topic="handleDeleteTopic"
        />
      </div>
      
      <!-- 中间 - 聊天内容区域 -->
      <div class="center-panel">
        <div class="chat-header">
          <div class="model-info">
            <span class="model-status" :class="{ active: isModelActive }"></span>
            <span class="model-name">{{ activeModelName }}</span>
            <el-tag size="small" :type="isLocalModel ? 'success' : 'primary'">
              {{ isLocalModel ? '本地模型' : '远程模型' }}
            </el-tag>
          </div>
          <div class="chat-actions">
            <el-tooltip content="清空对话">
              <el-button type="text" @click="handleClearChat">
                <i class="fa fa-trash-o"></i>
              </el-button>
            </el-tooltip>
          </div>
        </div>
        
        <div class="chat-messages" ref="messagesContainer">
          <div v-if="!activeTopic" class="empty-chat">
            <i class="fa fa-comments-o"></i>
            <p>选择一个主题开始对话，或创建一个新主题</p>
            <el-button type="primary" @click="handleCreateTopic">创建新主题</el-button>
          </div>
          <chat-message-list 
            v-else
            :messages="activeTopic.messages"
            :typing="isTyping"
          />
        </div>
        
        <div class="chat-input-area">
          <div class="input-toolbar">
            <el-tooltip content="上传图片">
              <el-button type="text" @click="triggerImageUpload">
                <i class="fa fa-image"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip content="上传文件">
              <el-button type="text" @click="triggerFileUpload">
                <i class="fa fa-file"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip :content="webSearchEnabled ? '已启用网络搜索' : '已禁用网络搜索'">
              <el-button 
                type="text" 
                @click="toggleWebSearch"
                :class="{ 'feature-enabled': webSearchEnabled }"
              >
                <i class="fa fa-globe"></i>
              </el-button>
            </el-tooltip>
            <input 
              type="file" 
              ref="imageInput" 
              accept="image/*" 
              style="display: none" 
              @change="handleImageUpload" 
            />
            <input 
              type="file" 
              ref="fileInput" 
              style="display: none" 
              @change="handleFileUpload" 
            />
          </div>
          
          <div class="input-container">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="输入您的问题或指令..."
              resize="none"
              @keydown.enter.exact.prevent="sendMessage"
            />
            <el-button 
              type="primary" 
              class="send-button" 
              :disabled="!userInput.trim() || isTyping"
              @click="sendMessage"
            >
              <i class="fa fa-paper-plane"></i>
            </el-button>
          </div>
          
          <div class="input-attachments" v-if="attachments.length > 0">
            <div 
              v-for="(attachment, index) in attachments" 
              :key="index"
              class="attachment-item"
            >
              <div class="attachment-preview">
                <img 
                  v-if="attachment.type.startsWith('image/')" 
                  :src="attachment.preview" 
                  class="image-preview"
                />
                <i 
                  v-else 
                  class="fa fa-file-text-o file-icon"
                ></i>
              </div>
              <div class="attachment-info">
                <div class="attachment-name">{{ attachment.name }}</div>
                <div class="attachment-size">{{ formatFileSize(attachment.size) }}</div>
              </div>
              <el-button 
                type="text" 
                class="remove-attachment" 
                @click="removeAttachment(index)"
              >
                <i class="fa fa-times"></i>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧 - 模型设置区域 -->
      <div class="right-panel">
        <model-settings 
          :active-model="activeModel"
          @model-changed="handleModelChanged"
        />
      </div>
    </div>
    
    <!-- 工具配置对话框 -->
    <el-dialog
      v-model="toolDialogVisible"
      :title="selectedTool ? selectedTool.name : '企业分析工具'"
      width="600px"
      destroy-on-close
    >
      <tool-config-form
        v-if="selectedTool"
        :tool="selectedTool"
        @execute="executeAnalysisTool"
        @cancel="toolDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 导入API接口
import { 
  getChatConversations, 
  getChatMessages, 
  sendChatMessage,
  createChatConversation,
  updateChatConversation,
  deleteChatConversation,
  uploadChatAttachment,
  clearChatMessages,
  getAIModelList
} from '/@/api/backend/yxerp/aichat';

// 导入组件
import AnalysisToolsBar from './components/enterprise/AnalysisToolsBar.vue';
import ChatTopicList from './components/enterprise/ChatTopicList.vue';
import ChatMessageList from './components/enterprise/ChatMessageList.vue';
import ModelSettings from './components/enterprise/ModelSettings.vue';
//import ToolConfigForm from './components/enterprise/ToolConfigForm.vue';

// 状态定义
const chatTopics = ref([]);
const activeTopicId = ref(null);
const userInput = ref('');
const isTyping = ref(false);
const messagesContainer = ref(null);
const webSearchEnabled = ref(false);
const attachments = ref([]);
const imageInput = ref(null);
const fileInput = ref(null);

// 工具相关状态
const toolDialogVisible = ref(false);
const selectedTool = ref(null);

// 模型相关状态
const activeModel = ref(null);
const isModelActive = ref(false);

// 计算属性
const activeTopic = computed(() => {
  return chatTopics.value.find(topic => topic.id === activeTopicId.value);
});

const activeModelName = computed(() => {
  return activeModel.value ? activeModel.value.name : '未选择模型';
});

const isLocalModel = computed(() => {
  return activeModel.value ? activeModel.value.type === 'local' : false;
});

// 生命周期钩子
onMounted(async () => {
  await loadChatTopics();
  await loadModelSettings();
  
  // 如果有主题，选择第一个
  if (chatTopics.value.length > 0) {
    activeTopicId.value = chatTopics.value[0].id;
    await loadMessages(activeTopicId.value);
  }
});

// 监听活动主题变化，滚动到底部
watch(activeTopic, () => {
  scrollToBottom();
});

// 方法定义
async function loadChatTopics() {
  try {
    const response = await getChatConversations(1); // 用户ID为1
    
    if (response.code === 1) {
      chatTopics.value = response.data.map(topic => ({
        id: topic.id.toString(),
        title: topic.title,
        lastTime: topic.updated_at,
        messageCount: topic.message_count,
        messages: []
      }));
    }
  } catch (error) {
    console.error('加载对话主题失败:', error);
    ElMessage.error('加载对话主题失败');
  }
}

async function loadMessages(topicId) {
  if (!topicId) return;
  
  try {
    const response = await getChatMessages(topicId);
    
    if (response.code === 1) {
      // 找到当前主题
      const topicIndex = chatTopics.value.findIndex(t => t.id === topicId);
      if (topicIndex !== -1) {
        // 更新消息列表
        chatTopics.value[topicIndex].messages = response.data.map(msg => ({
          id: msg.id,
          role: msg.role === 'assistant' ? 'ai' : msg.role,
          content: msg.content,
          time: msg.created_at,
          attachments: msg.attachments || []
        }));
      }
    }
  } catch (error) {
    console.error('加载消息失败:', error);
    ElMessage.error('加载消息失败');
  }
}

async function loadModelSettings() {
  try {
    const response = await getAIModelList();
    
    if (response.code === 1) {
      // 如果有默认模型，使用默认模型
      const defaultModel = response.data.find(model => model.is_default === 1);
      if (defaultModel) {
        activeModel.value = {
          id: defaultModel.id,
          type: 'remote',
          name: defaultModel.name,
          provider: defaultModel.provider || 'openai'
        };
        isModelActive.value = true;
      }
    }
  } catch (error) {
    console.error('加载模型设置失败:', error);
  }
}

function handleToolSelected(tool) {
  selectedTool.value = tool;
  toolDialogVisible.value = true;
}

async function executeAnalysisTool(tool, params) {
  toolDialogVisible.value = false;
  
  // 如果没有活动主题，创建一个新主题
  if (!activeTopic.value) {
    await handleCreateTopic();
  }
  
  // 构建工具提示词
  const prompt = `使用企业分析工具：${tool.name}\n\n${tool.generatePrompt(params)}`;
  
  // 发送工具提示词
  userInput.value = prompt;
  await sendMessage();
}

async function handleSelectTopic(topicId) {
  activeTopicId.value = topicId;
  await loadMessages(topicId);
}

async function handleCreateTopic(title = '新对话') {
  if (!activeModel.value) {
    ElMessage.warning('请先选择模型');
    return;
  }
  
  try {
    const topicData = {
      user_id: 1,
      title: title,
      model_id: activeModel.value.id,
      model_type: activeModel.value.type
    };
    
    const response = await createChatConversation(topicData);
    
    if (response.code === 1) {
      // 添加到主题列表
      const newTopic = {
        id: response.data.toString(),
        title: title,
        lastTime: new Date().toISOString(),
        messageCount: 0,
        messages: []
      };
      
      chatTopics.value.unshift(newTopic);
      activeTopicId.value = newTopic.id;
    } else {
      ElMessage.error(response.msg || '创建主题失败');
    }
  } catch (error) {
    console.error('创建主题失败:', error);
    ElMessage.error('创建主题失败');
  }
}

async function handleRenameTopic(topicId, newTitle) {
  try {
    const response = await updateChatConversation({
      id: topicId,
      title: newTitle
    });
    
    if (response.code === 1) {
      // 更新本地数据
      const topicIndex = chatTopics.value.findIndex(t => t.id === topicId);
      if (topicIndex !== -1) {
        chatTopics.value[topicIndex].title = newTitle;
      }
      ElMessage.success('重命名成功');
    } else {
      ElMessage.error(response.msg || '重命名失败');
    }
  } catch (error) {
    console.error('重命名主题失败:', error);
    ElMessage.error('重命名主题失败');
  }
}

async function handleDeleteTopic(topicId) {
  try {
    const response = await deleteChatConversation(topicId);
    
    if (response.code === 1) {
      // 从列表中移除
      chatTopics.value = chatTopics.value.filter(t => t.id !== topicId);
      
      // 如果删除的是当前活动主题，则选择第一个主题
      if (activeTopicId.value === topicId) {
        activeTopicId.value = chatTopics.value.length > 0 ? chatTopics.value[0].id : null;
      }
      
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除主题失败:', error);
    ElMessage.error('删除主题失败');
  }
}

async function handleClearChat() {
  if (!activeTopic.value) return;
  
  try {
    ElMessageBox.confirm('确定要清空当前对话的所有消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const response = await clearChatMessages(activeTopicId.value);
      
      if (response.code === 1) {
        // 清空本地消息
        const topicIndex = chatTopics.value.findIndex(t => t.id === activeTopicId.value);
        if (topicIndex !== -1) {
          chatTopics.value[topicIndex].messages = [];
          chatTopics.value[topicIndex].messageCount = 0;
        }
        ElMessage.success('已清空对话');
      }
    }).catch(() => {});
  } catch (error) {
    console.error('清空对话失败:', error);
    ElMessage.error('清空对话失败');
  }
}

async function sendMessage() {
  if (!userInput.value.trim() && attachments.value.length === 0) return;
  if (!activeModel.value) {
    ElMessage.warning('请先选择模型');
    return;
  }
  
  // 如果没有活动主题，创建一个新主题
  if (!activeTopic.value) {
    await handleCreateTopic();
    // 如果创建失败，直接返回
    if (!activeTopic.value) return;
  }
  
  const content = userInput.value.trim();
  const topicId = activeTopicId.value;
  userInput.value = '';
  
  // 先将用户消息添加到界面
  const userMessageId = Date.now();
  const userMessage = {
    id: userMessageId,
    role: 'user',
    content: content,
    time: new Date().toISOString(),
    attachments: [...attachments.value]
  };
  
  // 找到当前主题
  const topicIndex = chatTopics.value.findIndex(t => t.id === topicId);
  if (topicIndex !== -1) {
    chatTopics.value[topicIndex].messages.push(userMessage);
  }
  
  // 清空附件
  attachments.value = [];
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  // 显示AI正在输入
  isTyping.value = true;
  
  try {
    // 发送消息到服务器
    const messageData = {
      conversation_id: topicId,
      content: content,
      web_search: webSearchEnabled.value,
      attachments: userMessage.attachments.map(a => a.id)
    };
    
    const response = await sendChatMessage(messageData);
    
    if (response.code === 1) {
      // 找到当前主题
      const topicIndex = chatTopics.value.findIndex(t => t.id === topicId);
      if (topicIndex !== -1) {
        // 删除临时用户消息
        chatTopics.value[topicIndex].messages = chatTopics.value[topicIndex].messages.filter(
          msg => msg.id !== userMessageId
        );
        
        // 添加服务器返回的用户和AI消息
        const serverMessages = response.data.map(msg => ({
          id: msg.id,
          role: msg.role === 'assistant' ? 'ai' : msg.role,
          content: msg.content,
          time: msg.created_at,
          attachments: msg.attachments || []
        }));
        
        chatTopics.value[topicIndex].messages.push(...serverMessages);
        chatTopics.value[topicIndex].messageCount = chatTopics.value[topicIndex].messages.length;
        chatTopics.value[topicIndex].lastTime = new Date().toISOString();
      }
    } else {
      // 添加错误消息
      const errorMessage = {
        id: Date.now(),
        role: 'ai',
        content: `发送消息失败: ${response.msg || '未知错误'}`,
        time: new Date().toISOString(),
        error: true
      };
      
      const topicIndex = chatTopics.value.findIndex(t => t.id === topicId);
      if (topicIndex !== -1) {
        chatTopics.value[topicIndex].messages.push(errorMessage);
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    
    // 添加错误消息
    const errorMessage = {
      id: Date.now(),
      role: 'ai',
      content: `发送消息失败: ${error.message || '网络错误'}`,
      time: new Date().toISOString(),
      error: true
    };
    
    const topicIndex = chatTopics.value.findIndex(t => t.id === topicId);
    if (topicIndex !== -1) {
      chatTopics.value[topicIndex].messages.push(errorMessage);
    }
  } finally {
    isTyping.value = false;
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
}

function handleModelChanged(model) {
  activeModel.value = model;
  isModelActive.value = true;
  
  // 保存设置
  localStorage.setItem('enterprise_assistant_model', JSON.stringify(model));
  
  ElMessage.success(`已切换到${model.type === 'local' ? '本地' : '远程'}模型: ${model.name}`);
}

function toggleWebSearch() {
  webSearchEnabled.value = !webSearchEnabled.value;
  ElMessage.info(`${webSearchEnabled.value ? '启用' : '禁用'}网络搜索`);
}

function triggerImageUpload() {
  imageInput.value.click();
}

function triggerFileUpload() {
  fileInput.value.click();
}

// 处理文件上传
async function handleFileUpload(event) {
  const file = event.target.files[0];
  if (!file) return;
  
  const uploadedFile = await handleFileOrImageUpload(file);
  if (uploadedFile) {
    attachments.value.push(uploadedFile);
  }
  
  // 清空input以允许上传相同文件
  fileInput.value.value = '';
}

// 处理图片上传
async function handleImageUpload(event) {
  const file = event.target.files[0];
  if (!file) return;
  
  const uploadedFile = await handleFileOrImageUpload(file);
  if (uploadedFile) {
    attachments.value.push(uploadedFile);
  }
  
  // 清空input以允许上传相同文件
  imageInput.value.value = '';
}

// 处理文件或图片上传
async function handleFileOrImageUpload(file) {
  if (!file) return null;
  
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('conversation_id', activeTopic.value?.id || 0);
    
    const response = await uploadChatAttachment(formData);
    
    if (response.code === 1) {
      return {
        id: response.data.id,
        name: file.name,
        size: file.size,
        type: file.type,
        preview: file.type.startsWith('image/') ? URL.createObjectURL(file) : null
      };
    } else {
      ElMessage.error(response.msg || '上传文件失败');
      return null;
    }
  } catch (error) {
    console.error('上传文件失败:', error);
    ElMessage.error('上传文件失败');
    return null;
  }
}

function removeAttachment(index) {
  attachments.value.splice(index, 1);
}

function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  else if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
  else if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  else return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}

function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
}
</script>

<style scoped>
.enterprise-assistant {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background-color: #f6f8fc;
}

/* 顶部工具栏样式 */
.analysis-tools-section {
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8faff 0%, #eef2ff 100%);
  border-bottom: 1px solid #e0e5eb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

/* 主内容区样式 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧面板样式 */
.left-panel {
  width: calc(100% / 6);
  border-right: 1px solid #e0e5eb;
  overflow: hidden;
  background-color: #fff;
}

/* 中间面板样式 */
.center-panel {
  width: calc(100% / 6 * 3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 聊天头部样式 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #f8f9fb 100%);
  border-bottom: 1px solid #e0e5eb;
}

.model-info {
  display: flex;
  align-items: center;
}

.model-status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
  background-color: #f56c6c;
}

.model-status.active {
  background-color: #67c23a;
}

.model-name {
  font-weight: 500;
  margin-right: 8px;
  color: #303133;
}

/* 聊天消息区域样式 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f9fafc;
}

.empty-chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  text-align: center;
}

.empty-chat i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-chat p {
  margin-bottom: 16px;
}

/* 聊天输入区域样式 */
.chat-input-area {
  padding: 12px 16px;
  background-color: #fff;
  border-top: 1px solid #e0e5eb;
}

.input-toolbar {
  display: flex;
  margin-bottom: 8px;
}

.input-toolbar .el-button {
  font-size: 16px;
  color: #606266;
}

.input-toolbar .el-button.feature-enabled {
  color: #409eff;
}

.input-container {
  display: flex;
  align-items: flex-end;
}

.input-container .el-textarea {
  flex: 1;
}

.send-button {
  margin-left: 8px;
  height: 40px;
  width: 40px;
  padding: 0;
  border-radius: 20px;
}

.input-attachments {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-width: 200px;
}

.attachment-preview {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  overflow: hidden;
}

.image-preview {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.file-icon {
  font-size: 24px;
  color: #909399;
}

.attachment-info {
  flex: 1;
  min-width: 0;
}

.attachment-name {
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.attachment-size {
  font-size: 10px;
  color: #909399;
}

.remove-attachment {
  padding: 0 4px;
}

/* 右侧面板样式 */
.right-panel {
  width: calc(100% / 6 * 2);
  border-left: 1px solid #e0e5eb;
  overflow: hidden;
  background-color: #fff;
}
</style> 